#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "err.h"

using namespace std;
class tcpClient
{
public:
	// 构造函数
    tcpClient(const string& serverip, const uint16_t& serverport)
      :_serverip(serverip), _serverport(serverport), _sockfd(-1)
    {}
    // 客户端初始化
    void initClient()
    {
         _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_sockfd < 0)
        {
        cerr << "socket error : " << strerror(errno) << endl;
        exit(SOCKET_ERR);
        }
    }
    // 客户端启动
    void start()
    {
         // 2. connect
    struct sockaddr_in server;
    bzero(&server,sizeof(server));
    //memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(_serverport);
    server.sin_addr.s_addr=inet_addr(_serverip.c_str());
    //inet_aton(_serverip.c_str(), &(server.sin_addr));
    int ret=connect(_sockfd, (struct sockaddr*)&server, sizeof(server));
    if(ret==-1){
        cerr << "连接失败..." << endl;
    }
    // 3. 连接成功
    else
    {
        while(1){
            string line;
        cout << "Enter>>> ";
        getline(cin, line);

        write(_sockfd, line.c_str(), line.size());
        char buffer[1024];
        ssize_t s = read(_sockfd, buffer, sizeof(buffer)-1);
        if(s > 0)
        {
            buffer[s] = 0;
            cout << "server echo >>>" << buffer << endl;
        }
        else if(s == 0)
        {
            cerr << "server quit" << endl;
            break;
        }
        else {
            cerr << "read error: " << strerror(errno) << endl;
            break;
        }
        }
    }
    close(_sockfd);
    }
    // 析构函数
    ~tcpClient()
    {}
private:
	string _serverip;
    uint16_t _serverport;
    int _sockfd;
};
